Calling constructors for String
, BigInteger
, BigDecimal
and the objects used to wrap primitives is less
efficient and less clear than relying on autoboxing or valueOf
.
Consider simplifying when possible for more efficient and cleaner code.
Noncompliant code example
String empty = new String(); // Noncompliant; yields essentially "", so just use that.
String nonempty = new String("Hello world"); // Noncompliant
Double myDouble = new Double(1.1); // Noncompliant; use valueOf
Integer integer = new Integer(1); // Noncompliant
Boolean bool = new Boolean(true); // Noncompliant
BigInteger bigInteger1 = new BigInteger("3"); // Noncompliant
BigInteger bigInteger2 = new BigInteger("9223372036854775807"); // Noncompliant
BigInteger bigInteger3 = new BigInteger("111222333444555666777888999"); // Compliant, greater than Long.MAX_VALUE
BigDecimal bigDecimal = new BigDecimal("42.0"); // Compliant (see Exceptions section)
Compliant solution
String empty = "";
String nonempty = "Hello world";
Double myDouble = 1.1;
Integer integer = 1;
Boolean bool = true;
BigInteger bigInteger1 = BigInteger.valueOf(3);
BigInteger bigInteger2 = BigInteger.valueOf(9223372036854775807L);
BigInteger bigInteger3 = new BigInteger("111222333444555666777888999");
BigDecimal bigDecimal = new BigDecimal("42.0");
Exceptions
BigDecimal
constructor with a double
argument is ignored as using valueOf
instead might change the resulting
value. See S2111.